package com.js.myapp.system.activity;

// Created by JS on 2021/2/4.

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.js.basicpage.activity.BaseLoadingDialogActivity;
import com.js.basicutils.LogUtils;
import com.js.basicutils.NavigationBarUtil;
import com.js.basicutils.StatusBarUtil;
import com.js.basicutils.ToastUtils;
import com.js.myapp.R;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ScanQRCodeActivity extends BaseLoadingDialogActivity {

    private static final String TAG = "ScanQRCodeActivity";

    @BindView(R.id.fl_container)
    FrameLayout flContainer;
    @BindView(R.id.ll_input_code)
    LinearLayout llInputCode;
    @BindView(R.id.ll_light)
    LinearLayout llLight;

    private ScanQRCodeActivity mContext;
    private CaptureFragment captureFragment;
    private AlertDialog mInputDialog;

    private boolean isOpen = false; // 是否开启了闪光灯

    public static void start(Context context) {
        Intent intent = new Intent(context, ScanQRCodeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_qr_code);
        ButterKnife.bind(this);
        mContext = this;
        NavigationBarUtil.setSysNavigationColor(this, Color.parseColor("#141d26"));
//        NavigationBarUtil.hideBottomUI(getWindow().getDecorView());
        StatusBarUtil.setStatusBarColor(this, R.color.color_statusbar_bg);
        initView();
    }

    private void initView() {
        captureFragment = new CaptureFragment();
        CodeUtils.setFragmentArgs(captureFragment, R.layout.layout_scan_qr_code);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_container, captureFragment).commit();
    }

    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            if (result != null) {
                LogUtils.d(TAG, "扫码结果：" + result);
                ToastUtils.showToast(mContext, "扫码结果：" + result);
                captureFragment.restartCamera(); // 重置摄像头
            }
        }

        @Override
        public void onAnalyzeFailed() {
            LogUtils.d(TAG, "扫码结果：扫码失败！");
            ToastUtils.showToast(mContext, "扫码结果：扫码失败");
            captureFragment.restartCamera(); // 重置摄像头
        }
    };

    @OnClick({R.id.ll_input_code, R.id.ll_light})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_input_code:
                inputCode();
                break;
            case R.id.ll_light:
                switchLight();
                break;
        }
    }

    /**
     * 手动输入编码
     */
    private void inputCode() {
        if (mInputDialog == null) {
            mInputDialog = new AlertDialog.Builder(this).create();
            View view = View.inflate(this, R.layout.dialog_input_receive_code, null);
            TextView tvTitle = view.findViewById(R.id.tv_title);
            EditText etSampleCode = view.findViewById(R.id.et_sample_code);
            Button btnConfirm = view.findViewById(R.id.btn_confirm);
            Button btnCancel = view.findViewById(R.id.btn_cancel);
            tvTitle.setText("样品编码");

            btnConfirm.setOnClickListener(v -> {
                String code = etSampleCode.getText().toString().trim();
                if (TextUtils.isEmpty(code)) {
                    ToastUtils.showToast(mContext, "请输入编码~");
                    return;
                }
                LogUtils.d(TAG, "输入结果：" + code);
                ToastUtils.showToast(mContext, "输入结果：" + code);
                mInputDialog.dismiss();
            });
            btnCancel.setOnClickListener(v -> mInputDialog.dismiss());
            mInputDialog.setCanceledOnTouchOutside(false);
            mInputDialog.setView(view);
        }

//        dialog.setOnDismissListener(dialog1 -> captureFragment.restartCamera());
        mInputDialog.show();

        //下面这段代码应放在dialog.show()的后面，不然在6.0或者更低版本中报错：
        //requestFeature() must be called before adding content
        Window window = mInputDialog.getWindow();
        // 设置父布局为透明，以显现出自定义布局的圆角
        if (window != null) {
            View decorView = window.getDecorView();
            decorView.setBackgroundColor(Color.TRANSPARENT);
        }
    }

    /**
     * 手电筒开关
     */
    private void switchLight() {
        if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
            ToastUtils.showToast(this, "你的手机没有闪光灯!");
            return;
        }
        if (!isOpen) {
            CodeUtils.isLightEnable(true);
            isOpen = true;
        } else {
            CodeUtils.isLightEnable(false);
            isOpen = false;
        }
    }
}
